package edu.uoc.tdp.pac4.client.mantenimiento;

import edu.uoc.tdp.pac4.util.DateTimeUtils;
import edu.uoc.tdp.pac4.beans.Curso;
import edu.uoc.tdp.pac4.remote.Mantenimiento;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import edu.uoc.tdp.pac4.util.FieldLimit;

import edu.uoc.tdp.pac4.client.PnlMain;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import java.util.Date;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import java.io.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author eSupport Netbeans
 */
public class PnlMantenimientoCursoGestor extends javax.swing.JDialog 
{
    private Mantenimiento manager;
    private LanguageUtils language;

    private String ActionType;
   
    private Date now                = new Date();
    private SimpleDateFormat df     = new SimpleDateFormat("dd/MM/yyyy");
    private Curso curso             = null;
    private ArrayList<Curso> cursos = null;
    private int cursoID;
    private int NAME_LENGTH = 50;
   
    /**
      * Creates new form PnlGroupGestor
      */
    public PnlMantenimientoCursoGestor(PnlMantenimientoCursos parent, boolean modal, Mantenimiento manager, LanguageUtils language, String ActionType, int cursoID) 
    {
        super(parent, modal);
        initComponents();
      
        setLocationRelativeTo(null);

        this.manager    = manager;
        this.language   = language;
        this.ActionType = ActionType;
        this.cursoID    = cursoID;
      
        addaptToPreferences();

   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        cmdClose = new javax.swing.JButton();
        fldName = new javax.swing.JTextField();
        lblName = new javax.swing.JLabel();
        lblAsistencia = new javax.swing.JLabel();
        lblBiblio = new javax.swing.JLabel();
        lblPlan = new javax.swing.JLabel();
        cmdAccept = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tarPlan = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        tarBiblio = new javax.swing.JTextArea();
        lblDateIni = new javax.swing.JLabel();
        lblDateEnd = new javax.swing.JLabel();
        btnPlanDocente = new javax.swing.JButton();
        btnBibliografia = new javax.swing.JButton();
        fldAsistencia = new javax.swing.JFormattedTextField();
        fldDateIni = new javax.swing.JFormattedTextField();
        fldDateEnd = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jToolBar1.setRollover(true);

        cmdClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/arrow-curve-180.png"))); // NOI18N
        cmdClose.setText("Cerrar");
        cmdClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCloseActionPerformed(evt);
            }
        });

        lblName.setText("Nombre");

        lblAsistencia.setText("Minima Asistencia");

        lblBiblio.setText("Bibliografía");

        lblPlan.setText("Plan Docente");

        cmdAccept.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/ok_st_obj.gif"))); // NOI18N
        cmdAccept.setText("Acceptar");
        cmdAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAcceptActionPerformed(evt);
            }
        });

        tarPlan.setColumns(20);
        tarPlan.setLineWrap(true);
        tarPlan.setRows(5);
        jScrollPane1.setViewportView(tarPlan);

        tarBiblio.setColumns(20);
        tarBiblio.setLineWrap(true);
        tarBiblio.setRows(5);
        jScrollPane2.setViewportView(tarBiblio);

        lblDateIni.setText("Fecha Inicio");

        lblDateEnd.setText("Fecha Fin");

        btnPlanDocente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/disk--plus.png"))); // NOI18N
        btnPlanDocente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlanDocenteActionPerformed(evt);
            }
        });

        btnBibliografia.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/disk--plus.png"))); // NOI18N
        btnBibliografia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBibliografiaActionPerformed(evt);
            }
        });

        fldAsistencia.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));

        fldDateIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        fldDateIni.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        fldDateEnd.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        fldDateEnd.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmdAccept)
                        .addGap(45, 45, 45)
                        .addComponent(cmdClose))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblPlan)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnPlanDocente))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblDateIni)
                                    .addComponent(lblName))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(fldName, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                                    .addComponent(fldDateIni))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblBiblio)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnBibliografia))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblDateEnd)
                                    .addComponent(lblAsistencia))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fldAsistencia)
                                    .addComponent(fldDateEnd))))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblName)
                    .addComponent(lblAsistencia)
                    .addComponent(fldAsistencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDateIni)
                    .addComponent(lblDateEnd)
                    .addComponent(fldDateIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fldDateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnPlanDocente)
                            .addComponent(btnBibliografia))
                        .addComponent(lblPlan, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(lblBiblio, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdClose)
                    .addComponent(cmdAccept))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
   
    private boolean allDataFilled() {
        /*
         * Tanto para añadir  un usuario deberemos tener toda la información.
         * Para modificarlo, toda excepto el password, que es opcional
         * Esta función se encarga de asegurarse de que así sea.
         */
        if (fldName.getText().isEmpty()       || fldName.getText().equals(""))       {return false;}
        if (fldAsistencia.getText().isEmpty() || Integer.parseInt(fldAsistencia.getText()) < 0) {return false;}
        if (fldDateIni.getText().isEmpty()    || fldDateIni.getText().equals(""))    {return false;}
        if (fldDateIni.getText().isEmpty()    || fldDateIni.getText().equals(""))    {return false;}
        //if (tarPlan.getText().isEmpty()       || tarPlan.getText().equals(""))       {return false;}
        //if (tarBiblio.getText().isEmpty()     || tarBiblio.getText().equals(""))     {return false;}
        
        return true;
    }
    private void setLabelsLanguage() {
        /*
         * Definimos el texto de las labels del panel en función del idioma seleccionado
         */
        lblName.setText       (language.getProperty("mantenimiento.usermain.name"));
        lblAsistencia.setText (language.getProperty("mantenimiento.cursosmain.minasistencia"));
        lblBiblio.setText     (language.getProperty("mantenimiento.cursosmain.plandocente"));
        lblPlan.setText       (language.getProperty("mantenimiento.cursosmain.biblio")); 
        lblDateIni.setText    (language.getProperty("mantenimiento.cursosmain.fechaini"));
        lblDateEnd.setText    (language.getProperty("mantenimiento.cursosmain.fechaend"));
       
        if (this.ActionType.equalsIgnoreCase("Add")) {
            this.cmdAccept.setText(language.getProperty("mantenimiento.usermain.newUser"));
        }
        else if (this.ActionType.equalsIgnoreCase("Edit")){
            this.cmdAccept.setText(language.getProperty("mantenimiento.usermain.modUser"));
        }
        this.cmdClose.setText(language.getProperty("mantenimiento.usermain.back"));
    }
   
    private void addaptToPreferences() {
        /*
         * El mismo panel se usa para añadir/modificar usuarios, hay que adaptar ciertas características
         * en función de qué se solicite
         */
        this.setLabelsLanguage();
        
        this.fldName.setDocument(new FieldLimit(NAME_LENGTH));
       
        // Cambios Vinculados al tipo de llamada
        if (this.ActionType.equalsIgnoreCase("Add")) {
            this.addaptToAddCurso();
        } else if (this.ActionType.equalsIgnoreCase("Edit")) {
            this.addaptToEditCurso();
        }
    }
   
    private void addaptToAddCurso(){
        
        this.setTitle(language.getProperty("mantenimiento.main.title") + ". " + 
                      language.getProperty("mantenimiento.main.aula")  + ". " +
                      language.getProperty("mantenimiento.usermain.newUser"));
       
       /*
        * Cuando vamos a añadir un nuevo usuario los parametros (excepto Fecha de Registro)
        * se inicializan en blanco
        * 
        * El usuario de creación por defecto es Alumno, que debería ser el más abundante
        */
       fldName.setText       ("");
       fldAsistencia.setText ("");
       tarBiblio.setText     ("");
       tarPlan.setText       ("");
       fldDateIni.setText    ("");
       fldDateEnd.setText    ("");
            
       this.cmdAccept.setText(language.getProperty("mantenimiento.usermain.newUser"));
       
       try {
           cursos = manager.getCursosInactivos();
       }
       catch (SQLException ex) {
                 JOptionPane.showMessageDialog(null, 
                                               language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                               language.getProperty("app.title"), 
                                               JOptionPane.ERROR_MESSAGE);
        }
        catch (Exception ex) {
                 JOptionPane.showMessageDialog(null, 
                                               language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                               language.getProperty("app.title"), 
                                               JOptionPane.ERROR_MESSAGE);
        }
    }
   
    private void addaptToEditCurso(){
        
        this.setTitle(language.getProperty("mantenimiento.main.title") + ". " + 
                      language.getProperty("mantenimiento.main.user")   + ". " +
                      language.getProperty("mantenimiento.usermain.modUser"));
       
       /*
        * Cuando vamos a modificar un usuario, inicializamos los formularios con los valores
        * que tiene el usuario
        */
        try {
            this.curso = manager.getCurso(this.cursoID);
            
            this.fldName.setText       (curso.getNombre());
            this.fldAsistencia.setText ("" + curso.getMinasistencia());
            this.fldDateIni.setText    (df.format(curso.getFechaInicio()));
            this.fldDateEnd.setText    (df.format(curso.getFechaFin()));
            this.tarPlan.setText       (curso.getPlandocente());
            this.tarBiblio.setText     (curso.getBibliografia());
        }
        catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
        } 
        catch (Exception ex) {
                JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);

        }
           
        this.cmdAccept.setText(language.getProperty("mantenimiento.usermain.modUser")); 
    }
   
   private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCloseActionPerformed

    /*
     * Cerramos el formulario
     */
    this.dispose();

   }//GEN-LAST:event_cmdCloseActionPerformed

    private void cmdAddCursoAction() {
        /*
         * Gestión de Añadir Nuevo Usuario
         * Creamos una instancia Usuario con toda la info recibida y luego la pasamos al manager
         * para que la incluya en la BD
         * 
         * Si añadimos correctamente se cierra el panel
         */
        
        Date iniCurso = DateTimeUtils.strToDate(this.fldDateIni.getText());
        Date endCurso = DateTimeUtils.strToDate(this.fldDateEnd.getText());
        
        if (!DateTimeUtils.isDate(this.fldDateIni.getText()) || 
            !DateTimeUtils.isDate(this.fldDateEnd.getText())) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("mantenimiento.err.date.mal"), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
        else if (endCurso.before(iniCurso)) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("mantenimiento.err.date.reverse"), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
        try {
            this.curso = new Curso();
            
            curso.setNombre(this.fldName.getText());
            curso.setMinasistencia(new Integer(this.fldAsistencia.getText()));
            curso.setFechaInicio(iniCurso);
            curso.setFechaFin(endCurso);
            curso.setPlandocente(this.tarPlan.getText());
            curso.setBibliografia(this.tarBiblio.getText());
            
            for (Curso oldCurso : cursos) {
                if (curso.getNombre().equalsIgnoreCase(oldCurso.getNombre())) {
                    if (manager.undeleteCurso(oldCurso.getId())) {
                        JOptionPane.showMessageDialog(null, language.getProperty("mantenimiento.msg.add.oldcurs"),
                                              "Información", JOptionPane.INFORMATION_MESSAGE);
                        this.dispose();
                        return;
                    }
                }
            }
            
            if (manager.addCurso(curso)) {
                JOptionPane.showMessageDialog(null, language.getProperty("mantenimiento.msg.add.curs"),
                                              "Información", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
            
        }
        catch (SQLException ex) {
                 JOptionPane.showMessageDialog(null, 
                                               language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                               language.getProperty("app.title"), 
                                               JOptionPane.ERROR_MESSAGE);
        }
        catch (Exception ex) {
                 JOptionPane.showMessageDialog(null, 
                                               language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                               language.getProperty("app.title"), 
                                               JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void cmdModCursoAction() {
        /*
         * Gestión de odificar Usuario
         * Creamos una instancia Usuario con toda la info recibida y luego la pasamos al manager
         * para que la actualize la BD (no se accede al UserID)
         * 
         * Para la modificacion solicitaremos confirmación
         * 
         * Si modificamos correctamente se cierra el panel
         */
        try {
            
            Date iniCurso = DateTimeUtils.strToDate(this.fldDateIni.getText());
            Date endCurso = DateTimeUtils.strToDate(this.fldDateEnd.getText());
        
        if (!DateTimeUtils.isDate(this.fldDateIni.getText()) || 
            !DateTimeUtils.isDate(this.fldDateEnd.getText())) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("mantenimiento.err.date.mal"), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
        else if (endCurso.before(iniCurso)) {
            JOptionPane.showMessageDialog(null, 
                                          "fchas mal orden", 
                                          language.getProperty("mantenimiento.err.date.reverse"), 
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
            
            Curso new_curso = new Curso();
            
            new_curso.setId(this.cursoID);
            new_curso.setNombre(this.fldName.getText());
            new_curso.setMinasistencia(new Integer(this.fldAsistencia.getText()));
            new_curso.setFechaInicio(iniCurso);
            new_curso.setFechaFin(endCurso);
            new_curso.setBibliografia(this.tarBiblio.getText());
            new_curso.setPlandocente(this.tarPlan.getText());
            
            Object[] options = {language.getProperty("opt.si"), language.getProperty("opt.no")};
            int reply = JOptionPane.showOptionDialog(this, language.getProperty("mantenimiento.msg.confirm"), language.getProperty("app.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, now);
            if (reply == 0) {
                if (manager.updateCurso(new_curso)) {
                    JOptionPane.showMessageDialog(null, language.getProperty("mantenimiento.msg.modif"),
                                                  "Información", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            this.dispose();
        }
        catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void cmdAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAcceptActionPerformed
        /*
         * Las acciones sólo se llevaran a cabo si tenemos TODOS los campos llenos
         */
        if (!this.allDataFilled()) {
            JOptionPane.showMessageDialog(null, 
                                          language.getProperty("mantenimiento.err.fields"), 
                                          language.getProperty("app.title"), 
                                          JOptionPane.ERROR_MESSAGE);
        } else {
            if (this.ActionType.equalsIgnoreCase("Add")) {
                this.cmdAddCursoAction();
            }
            else if (this.ActionType.equalsIgnoreCase("Edit")) {
                this.cmdModCursoAction();
            }
        }
    }//GEN-LAST:event_cmdAcceptActionPerformed

    /**
     * Método que carga un html en el cuadro de texto
     * @param evt 
     */
    private void btnPlanDocenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlanDocenteActionPerformed
        
        BufferedReader reader = null;
        StringBuilder contenido = new StringBuilder();
        final JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filtroHTML =
                   new FileNameExtensionFilter("HTML, html","html","htm");
        
        fc.setMultiSelectionEnabled(false);
        fc.setAcceptAllFileFilterUsed(false);        
        fc.setFileFilter(filtroHTML);
        int retval = fc.showOpenDialog(this);        
        if (retval == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();            
            try 
            {   
                if(fc.getFileFilter() == filtroHTML)
                {
                    reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
                    String text = null;
                    while((text = reader.readLine()) != null)
                        contenido.append(text);
   
                }
                else
                {
                    JOptionPane.showMessageDialog(null, 
                                              language.getProperty("mantenimiento.err.extension"), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);
                }
                
            }catch(IOException ex)
            {
                
                JOptionPane.showMessageDialog(null, 
                                              language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);
                
            }finally 
            {
                try
                {
                    if(reader != null)
                        reader.close();
                    
                }catch(IOException ex)
                {
                   JOptionPane.showMessageDialog(null, 
                                              language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);   
                }
                  
                tarPlan.setText(contenido != null ? contenido.toString().replace("'", "''") : "");
            }
          
        }         
    }//GEN-LAST:event_btnPlanDocenteActionPerformed

    /**
     * Método que carga un html en el cuadro de texto.
     * @param evt 
     */
    private void btnBibliografiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBibliografiaActionPerformed
        BufferedReader reader = null;
        StringBuilder contenido = new StringBuilder();
        final JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filtroHTML =
                   new FileNameExtensionFilter("HTML, html","html","htm");
        
        fc.setMultiSelectionEnabled(false);
        fc.setAcceptAllFileFilterUsed(false);        
        fc.setFileFilter(filtroHTML);
        int retval = fc.showOpenDialog(this);        
        if (retval == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();            
            try 
            {   
                if(fc.getFileFilter() == filtroHTML)
                {
                    reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
                    String text = null;
                    while((text = reader.readLine()) != null)
                        contenido.append(text);
                       
                }
                else
                {
                    JOptionPane.showMessageDialog(null, 
                                              language.getProperty("mantenimiento.err.extension"), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);
                }
                
            }catch(IOException ex)
            {
                
                JOptionPane.showMessageDialog(null, 
                                              language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);
                
            }finally 
            {
                try
                {
                    if(reader != null)
                        reader.close();
                    
                }catch(IOException ex)
                {
                   JOptionPane.showMessageDialog(null, 
                                              language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                              language.getProperty("app.title"), 
                                              JOptionPane.ERROR_MESSAGE);   
                }
                  
                tarBiblio.setText(contenido != null ? contenido.toString().replace("'", "''") : "");
            }
          
        }
    }//GEN-LAST:event_btnBibliografiaActionPerformed
   
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBibliografia;
    private javax.swing.JButton btnPlanDocente;
    private javax.swing.JButton cmdAccept;
    private javax.swing.JButton cmdClose;
    private javax.swing.JFormattedTextField fldAsistencia;
    private javax.swing.JFormattedTextField fldDateEnd;
    private javax.swing.JFormattedTextField fldDateIni;
    private javax.swing.JTextField fldName;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblAsistencia;
    private javax.swing.JLabel lblBiblio;
    private javax.swing.JLabel lblDateEnd;
    private javax.swing.JLabel lblDateIni;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblPlan;
    private javax.swing.JTextArea tarBiblio;
    private javax.swing.JTextArea tarPlan;
    // End of variables declaration//GEN-END:variables
}
